package com.hugoo.imp.buzz;

import com.hugoo.core.db.ImpProc;
import com.hugoo.core.util.FileEncode;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

/**
 *
 * @author Lovelock.Chan
 */
public class TxtImpBuzz extends ImpInfo {

    public TxtImpBuzz(String _sid, String impFilePath, String _scod, Map<String, String> parax) {
        super(_sid, impFilePath, _scod, parax);
    }

    @Override
    public ImpProc impProc() {
        return new ImpProc() {
            @Override
            public String procSql() {
                return kf;
            }

            @Override
            public void preProc(PreparedStatement psmt) throws FileNotFoundException, IOException, SQLException {
                BufferedReader fr = new FileEncode(impFilePath).getBufferedReader();
                String t;
                String[] x;
                int l = _cols.length;//tc[0].length - 3;
                int i = 0, j = 0, p = 1;
                while (fr.ready()) {
                    if (j < 3) {
                        t = fr.readLine();
                        if (t.endsWith("|")) {//1|2|3|4||x
                            p = 2;
                        }
                        t += "|x";
                    } else {
                        t = fr.readLine() + "|x";
                    }
                    x = t.split("\\|");
                    if ((x.length - p) == l && !t.contains(col_title)) {//去标题
                        for (int z = 0; z < l; z++) {
                            psmt.setString((z + 1), x[z].trim());//--导入文本不支持头尾空格
                        }
                        psmt.addBatch();
                        i++;
                        if (i % 30000 == 0) {
                            psmt.executeBatch();
                            psmt.getConnection().commit();
                            psmt.clearBatch();
                        }
                    } else {
                        j++;
                        continue;
                    }
                }
                if (i % 30000 > 0) {
                    psmt.executeBatch();
                }
                log.info("本次导入数据，导入【" + i + "】条记录，省略【" + j + "】条记录");
                fr.close();
            }
        };
    }
}
